<template>
  <el-dialog
    :model-value="show"
    title="分配角色"
    width="30%"
    center
    @close="emit('hide')"
  >
    <el-select
      v-model="list"
      multiple
      placeholder="Select"
      style="width: 240px"
    >
      <el-option
        v-for="item in roles"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="emit('hide')">取消</el-button>
        <el-button type="primary" @click="submit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, watch } from "vue";
import { userRoleAPI, userRoleByIdAPI, userRoleUpdataAPI } from "./api";
//选择器参数
const list = ref<number[] | any>([]);
//选择器数组
const roles = ref<{ label: string; value: number }[] | any>([]);
//获取父组件传递过来的数据
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  id: {
    type: Number,
    default: 0,
  },
});
//获取父组件传递过来的方法
const emit = defineEmits(["hide"]);
//获取角色请求
userRoleAPI().then((res) => {
  if (res.code === 200) {
    roles.value = res.data.map((item) => ({
      label: item.name,
      value: item.id,
    }));
  }
});
//确认
const submit = () => {
  ElMessageBox.confirm("此操作将分配当前用户角色, 是否继续?", "分配用户角色", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(() => {
      userRoleUpdataAPI(props.id, list.value).then((res) => {
        if (res.code === 200) {
          //提示修改成功
          ElMessage.success("修改角色成功");
          //关闭对话框
          emit("hide");
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消成功",
      });
    });
};

//监听传递进来的id
watch(
  () => props.id,
  () => {
    if (props.id === 0) return;
    userRoleByIdAPI(props.id).then((res) => {
      if (res.code === 200) {
        list.value = res.data.map((item) => item.id);
      }
    });
  }
);
</script>
<style lang="less" scoped></style>
